<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="'任务选择'" class="tl-dialog projectPlanTreeRef" width="80%" top="10px" :append-to-body="true" :modal-append-to-body="true" @open="open" @close="close" :style="cssVars" destroy-on-close>
    <el-row>
      <!-- 树 -->
      <el-col :span="5" class="tl-left-tree">
        <el-input v-model="queryLeftParam.qry_nameorcode" placeholder="输入名称或编号" class="search-input">
          <el-button type="primary" slot="append" icon="el-icon-search" @click="getLeftList" :loading="leftLoading"></el-button>
        </el-input>
        <el-scrollbar :style="{ height: tableHeight }" v-loading="leftLoading">
          <el-tooltip class="item" effect="dark" v-for="(item, index) in leftList" :key="index" :content="`${index + 1}.${item.projectname}(${item.projectcode})`" placement="right" :open-delay="1000">
            <el-col :span="24"  :key="index" class="left-item" :class="[chooseProjectId === item.id ? 'active' : '', 'left-item']"  @click.native="chooseProject(item)">
              {{`${index + 1}.${item.projectname}(${item.projectcode})`}}
            </el-col>
          </el-tooltip>
        </el-scrollbar>
      </el-col>

      <el-col :span="19">
        <el-button type="text" @click="selectAllTask()">{{ selectAll ? '取消全选' : '一键全选'}}</el-button>
        <el-card>
          <el-row>
            <el-table ref="mainTable" class="tl-table" :height="tableHeight" resizable-key="tableHeight" @expand-change="()=>{return false}"  v-loading="rightLoading" :data="datas" style="width: 100%;" @selection-change="doSelectChange" @sort-change="doSortChange" row-key="id" border fit  default-expand-all>
              <el-table-column type="expand">
                <template slot-scope="props">
                  <div style="margin-left:102px;padding-right: 5px">
                    <el-table class="tl-table" :ref="'taskTable' + props.$index"  :data="props.row.tasklist" row-key="id" border fit>
                      <el-table-column type="selection" width="55"></el-table-column>
                      <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
                      <el-table-column prop="taskname" label="任务名称" min-width="200px"  align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
                      <el-table-column prop="tasktarget" label="任务目标" width="120px"  align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
                      <el-table-column prop="taskdetail" label="任务内容" width="200px"  align="center" header-align="center" :show-overflow-tooltip="true"> </el-table-column>
                      <el-table-column prop="responsible" label="责任人" width="80px"  align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
                      <el-table-column prop="planstartdate" label="计划开始日期" width="120px"  align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"> </el-table-column>
                      <el-table-column prop="planenddate" label="计划完成日期" width="120px"  align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"> </el-table-column>
                    </el-table>
                  </div>
                </template>
              </el-table-column>
              <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
              <el-table-column prop="milepostname" label="里程碑及任务名称" min-width="200px"  align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="deliverable" label="交付成果"  width="200px" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="dispmilepoststate" label="里程碑及任务状态" width="140px"  align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="responsible" label="责任人" width="80px"  align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="planfinishtime" label="计划达成日期" width="120px"  align="center" header-align="center" :show-overflow-tooltip="true" :formatter="dateFormat"></el-table-column>
            </el-table>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
    <el-button @click="visible = false">取 消</el-button>
    <el-button type="primary" @click="confirmTaskInfo" :loading="confirmLoading">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_ref_list } from '@tapui/mixins/mixin_ref_list'
/** 工具类**/
import { getAction, putAction, postAction, deleteAction } from "@tapui/utils/http"

export default {
  name: "ProjectPlanTreeRef",
  mixins: [mixin_ref_list],
  data() {
    return {
      urlPrefix: "/mpm/project/",
      url: {
        leftList: '/mpm/project/refList',
        rightList: '/mpm/projectMilepost/getMilePostForOldProjectAdd',
        saveOldProjectInfo: '/mpm/projectMilepost/saveOldProjectInfo'
      },
      visible: false,
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        pageSizes: ['10', '50', '100'],
        totalCount: 0
      },
      // 排序参数
      sorterInfo: {
        sidx: "sortcode",
        sord: "desc"
      },
      allChecked: [],
      queryLeftParam: {
        qry_projectref: '1'
      },
      leftLoading: false, // 左侧列表loading
      rightLoading: false, // 右列表loading
      confirmLoading: false, // 确定loading
      leftList: [], // 左侧列表数据
      chooseProjectId: 0, // 选中项目id
      chooseProjectCode: '', // 选中项目code
      selectionTaskRows: [], // 选中任务
      selectedTaskRowKeys: [],
      tableHeight: '440px',
      selectAll: false
    }
  },
  props: {
    projectInfo: {},
    planId: {}
  },
  computed: {
    // 全局样式
    cssVars() {
      return {
        "--themeColor": this.$store.getters.theme
      }
    }
  },
  methods: {
    /**
     * 获取左列表数据
     **/
    getLeftList() {
      this.leftLoading = true
      getAction(this.url.leftList, this.queryLeftParam)
        .then((res) => {
          if (res.success) {
            this.leftList = res.result.dataList
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.leftLoading = false
        })
        .catch((err) => {
          this.leftLoading = false
        })
    },
    /**
     * 打开dialog
     **/
    open() {
      this.getLeftList()
    },
    /**
     * 选择销售项目
     **/
    chooseProject(info) {
      if (this.chooseProjectId === info.id || this.rightLoading) {
        return
      }
      this.selectAll = false
      this.chooseProjectId = info.id
      this.chooseProjectCode = info.projectcode
      this.getChooseMilePost()
    },
    /**
     * 选择销售项目后加载对应的里程碑以及任务
     **/
    getChooseMilePost() {
      this.rightLoading = true
      getAction(this.url.rightList, { code: this.chooseProjectCode })
        .then((res) => {
          if (res.success) {
            this.datas = res.result
            this.$nextTick(() => {
              // 禁用折叠功能
              let btnCollection = document.getElementsByClassName("el-table__expand-icon--expanded")
              let arr = Array.from(btnCollection)
              arr.forEach((item) => {
                item.style.pointerEvents = 'none'
              })
            })
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.rightLoading = false
        })
        .catch((err) => {
          this.rightLoading = false
          this.$tap.alert(err.message, 'warning')
        })
    },
    /**
     * 获取选中任务
     **/
    getTaskSelectChange() {
      this.selectionTaskRows = []
      for (let refObj in this.$refs) {
        if (refObj.includes("taskTable") && this.$refs[refObj]) {
          this.selectionTaskRows = this.selectionTaskRows.concat(this.$refs[refObj].selection)
        }
      }
    },
    /**
     * 确认操作
     **/
    confirmTaskInfo() {
      if (this.chooseProjectCode === '') {
        this.$tap.alert("请选择销售项目！", 'warning')
        return
      }
      // 获取选中任务
      this.getTaskSelectChange()
      if (this.selectionTaskRows.length <= 0) {
        this.$tap.alert("请选择任务！", 'warning')
        return
      }
      const milePostCodes = new Set()
      let taskIds = []
      this.selectionTaskRows.forEach(item => {
        taskIds.push(item.id)
        milePostCodes.add(item.milepostcode)
      })
      let postParam = {
        milePostCodes: [...milePostCodes].join(","),
        taskIds: taskIds.join(","),
        projectCode: this.projectInfo.projectcode,
        projectName: this.projectInfo.projectname,
        planId: this.planId
      }
      this.confirmLoading = true
      postAction(this.url.saveOldProjectInfo, postParam)
        .then((res) => {
          this.$tap.message("添加成功")
          this.$emit("refreshData")
          this.confirmLoading = false
        })
        .catch((err) => {
          this.$tap.alert(err.message, 'warning')
          this.confirmLoading = false
        })
    },
    close() {
      this.leftList = []
      this.chooseProjectId = 0
      this.chooseProjectCode = ''
      this.datas = []
    },
    /**
     * 全选功能
     */
    selectAllTask() {
      if (this.chooseProjectCode === '') {
        this.$tap.alert("请选择销售项目！", 'warning')
        return
      }
      this.selectAll = !this.selectAll
      for (let refObj in this.$refs) {
        if (refObj.includes("taskTable") && this.$refs[refObj]) {
          if ((this.$refs[refObj].selection.length !== this.$refs[refObj].data.length) && this.selectAll) {
            this.$refs[refObj].toggleAllSelection()
          } else if (this.selectAll === false) {
            this.$refs[refObj].toggleAllSelection()
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .tl-dialog /deep/ .el-dialog__body {
    padding: 5px 15px !important;
    /*height: 70vh;*/
    /*overflow: auto;*/
  }
  .left-item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-top: 10px;
    cursor: pointer;
    padding: 3px;
    border-radius: 5px;
  }
  .active {
    background-color: var(--themeColor);
    color: #ffffff;
  }
  .tl-dialog /deep/ .el-button--primary {
    color: #FFF!important;
    background-color: #0A6ED2!important;
    border-color: #0A6ED2!important;
  }
  .tl-table /deep/ .el-table__empty-block {
     padding-left: 0;
  }
  .tl-table /deep/ .el-table__empty-text {
     margin: 0 auto!important;
     width: 60px!important;
  }
</style>
